<?php

$cmd = $_REQUEST['cmd'] ?? null;
$log_file = __DIR__ . '/log.txt';

if (!empty($_REQUEST))
{
    foreach ($_REQUEST as &$_rval)
    {
        $_rval = trim($_rval);
    }
}

if ($cmd === 'checkPHP')
{
    checkPHP();
} elseif ($cmd === 'checkDB')
{
    $dbhost = $_REQUEST['host'] ?? '';  // mysql服务器主机地址
    $dbport = $_REQUEST['port'] ?? '';
    $dbname = $_REQUEST['database'] ?? '';            // mysql用户名
    $dbuser = $_REQUEST['username'] ?? '';            // mysql用户名
    $dbpass = $_REQUEST['password'] ?? '';          // mysql用户名密码
    try {
        $pdo = new PDO("mysql:host={$dbhost}:{$dbport}", $dbuser, $dbpass); //创建一个pdo对象
    } catch (Exception $exc) {
        exit(json_encode([
            'code' => 4001,
            'message' => '<font color="red">数据库连接失败：' . $exc->getMessage() . '</font>',
        ]));
    }
    exit(json_encode([
        'code' => 200,
        'message' => '<font color="green">数据库连接成功！</font>',
    ]));
} else
{
    $dbhost = $_REQUEST['host'] ?? '';
    $dbport = $_REQUEST['port'] ?? '';
    $dbname = $_REQUEST['database'] ?? '';
    $dbuser = $_REQUEST['username'] ?? '';
    $dbpass = $_REQUEST['password'] ?? '';

    try {
        $pdo = new PDO("mysql:host={$dbhost}:{$dbport}", $dbuser, $dbpass); //创建一个pdo对象
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{$dbname}'";
        $result = $pdo->query($sql)->fetch();
        if (is_bool($result) && !$result)
        {
            $pdo->exec("set names 'utf8mb4'");
            $sql = "CREATE DATABASE {$dbname}";
            $pdo->exec($sql);
            file_put_contents($log_file, "创建数据库成功：{$dbname}\n");
        }
    } catch (Exception $exc) {
        exit(json_encode([
            'code' => 4001,
            'message' => '<font color="red">数据库连接失败：' . $exc->getMessage() . '</font>',
            'data' => [$exc->getCode()]
        ]));
    }

    try {
        $sql = file_get_contents(__DIR__ . '/../../import.sql');
        $pdo = new PDO("mysql:host={$dbhost}:{$dbport};dbname={$dbname}", $dbuser, $dbpass); //创建一个pdo对象
        $pdo->exec($sql);
        file_put_contents($log_file, "数据表和测试数据安装成功。\n", FILE_APPEND);
    } catch (Exception $exc) {
        exit(json_encode([
            'code' => 4001,
            'message' => '<font color="red">错误：' . $exc->getMessage() . '</font>',
            'data' => [$exc->getCode()]
        ]));
    }

    try {
        $imgfile = __DIR__ . '/../../storage/install/products_images.tar';
        $phar = new \PharData($imgfile);
        $phar->extractTo(__DIR__ . '/../../storage/app/public', null, true);
        file_put_contents($log_file, "产品测试图片安装成功。\n", FILE_APPEND);
    } catch (Exception $exc) {
        file_put_contents($log_file, "<font color='red'>产品测试图片安装失败。</font>\n", FILE_APPEND);
    }

    if (file_exists(__DIR__ . '/../storage'))
    {
        file_put_contents($log_file, "符号软链接已存在：public/storage。\n", FILE_APPEND);
    } else
    {
        if (function_exists('symlink'))
        {
            $target = dirname(dirname(__DIR__)) . '/storage/app/public';
            $link = dirname(__DIR__) . '/storage';
            @symlink($target, $link);
            file_put_contents($log_file, "符号软链接创建成功：public/storage\n", FILE_APPEND);
        } else
        {
            file_put_contents($log_file, "<font color='red'>符号软链接创建失败：public/storage，原因：函数 symlink <font color='red'>已禁用</font>。</font>\n", FILE_APPEND);
        }
    }

    exit(json_encode([
        'code' => 200,
        'message' => '<font color="green">安装成功。</font>',
    ]));
}

function checkPHP()
{
    $data[] = [
        'v1' => 'gd 扩展',
        'v2' => extension_loaded('gd') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'mysqli 扩展',
        'v2' => extension_loaded('mysqli') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'pdo_mysql 扩展',
        'v2' => extension_loaded('pdo_mysql') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'curl 扩展',
        'v2' => extension_loaded('curl') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'openssl 扩展',
        'v2' => extension_loaded('openssl') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'symlink 函数',
        'v2' => function_exists('symlink') ? '<font color="green">已启用</font>' : '<font color="red">已禁用</font>',
    ];
    $data[] = [
        'v1' => 'bootstrap 文件夹',
        'v2' => is_writable(dirname(dirname(__DIR__)) . '/bootstrap') ? '<font color="green">可读写</font>' : '<font color="red">不可读写</font>',
    ];
    $data[] = [
        'v1' => 'storage 文件夹',
        'v2' => is_writable(dirname(dirname(__DIR__)) . '/storage') ? '<font color="green">可读写</font>' : '<font color="red">不可读写</font>',
    ];

    exit(json_encode([
        'code' => 200,
        'message' => 'success',
        'data' => [
            'gd' => $gd,
            'mysqli' => $mysqli,
            'pdo_mysql' => $pdo_mysql,
            'curl' => $curl,
            'openssl' => $openssl,
        ],
        'list' => $data,
    ]));
}
